#!/bin/bash
set -euo pipefail
LOG_FILE="/root/scripts/archive_es_index_$(date +%Y%m%d).log"
declare -A my_dict
maxarchivetime1=$(date -d '7 months ago' '+%Y-%m')
maxarchivetime2=$(date -d '6 months ago' '+%Y-%m')
maxarchivetime3=$(date -d '3 months ago' '+%Y-%m')
maxarchivetime4=$(date -d '4 months ago' '+%Y-%m')
maxarchivetime5=$(date -d '2 months ago' '+%Y-%m')
WEBHOOK_URL="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abdjfhk29374529skdhfks"
send_text_message() {
  local content="$1"
  
  # 构造JSON数据
  local json_data
  json_data=$(cat <<EOF
{
  "msgtype": "text",
  "text": {
    "content": "$content"
  }
}
EOF
)
  # 发送请求
  curl -s -X POST "$WEBHOOK_URL" \
    -H "Content-Type: application/json" \
    -d "$json_data"
}
ES_HOST="http://127.0.0.1:9200"
ES_USER="user"  # ES用户名
ES_PASS="password"  # ES密码
SNAPSHOT_REPO="snapname"
SNAPSHOT_NAME="dba_snap_$(date +%Y%m%d%H%M%S)"
HOST='127.0.0.1'
USER='root' 
PASS='password'
DB='test'
es_id="es-rdkjl2H"
my_dict=(["account_"]=$maxarchivetime1  ["flow_"]=$maxarchivetime1 ["inventory__"]=$maxarchivetime1 ["difference_bill_"]=$maxarchivetime2  ["record_"]=$maxarchivetime3 ["work_"]=$maxarchivetime3 ["reduce_"]=$maxarchivetime3 ["product_"]=$maxarchivetime4 )

opearetime=`date "+%Y-%m-%d %H:%M:%S"`
LOGSQL="INSERT INTO t_oparea_es_task_log (task_id, task_name, index_name, action_name, oparea_date, status, create_date, modifyTime, remark) VALUES('-999','','','1',\"$opearetime\",'1',\"$opearetime\",\"$opearetime\",'');"
mysql -h$HOST -u$USER -p$PASS $DB -N -s -e "$LOGSQL"
tasklog_id=$(mysql -h$HOST -u$USER -p$PASS $DB -N -s  -e "select id from t_oparea_es_task_log where task_id=-999 order by id desc limit 1;")
if [ -z "${tasklog_id}" ]; then
  echo "插入日志表失败">>${LOG_FILE}
  exit
fi
snapindexs=''
for key in "${!my_dict[@]}"; do
  indexname="${key}${my_dict[$key]}"
  queryresult=$(curl -sS -u "$ES_USER:$ES_PASS" -X GET "$ES_HOST/${indexname}/_alias" -H 'Content-Type: application/json')
  aliases_value=$(echo "$queryresult" | grep -o '"aliases":{[^}]*}' | sed 's/"aliases"://')
  if [ "$aliases_value" == "{}" ]; then
    [[ ${snapindexs} == "" ]] && snapindexs="${indexname}" || snapindexs="${snapindexs},$indexname"
  fi
done
echo $snapindexs>>${LOG_FILE}
# 创建快照（带认证）
curl -u "$ES_USER:$ES_PASS" -X PUT "$ES_HOST/_snapshot/$SNAPSHOT_REPO/$SNAPSHOT_NAME?wait_for_completion=true" -H 'Content-Type: application/json' -d'
{"indices": "'"${snapindexs}"'",  "ignore_unavailable": true,  "include_global_state": false}'
if [ $? -ne 0 ]; then
   message="快照分拣实例任务失败,退出任务,请重新执行"
   echo $message>>${LOG_FILE}
   send_text_message $message
   exit
fi
# ===== 2. 监控快照状态 =====
TMP_FILE=$(mktemp)
MAX_RETRIES=60   # 最���重试次数（每10秒检测一次 ≈ 10分钟超时）
RETRY_INTERVAL=30

for ((i=1; i<=MAX_RETRIES; i++)); do
  curl -sS  -u "$ES_USER:$ES_PASS" "${ES_HOST}/_snapshot/${SNAPSHOT_REPO}/${SNAPSHOT_NAME}/_status" > "$TMP_FILE"
  SNAPSHOT_STATE=$(jq -r '.snapshots[0].state' "$TMP_FILE")
  case "$SNAPSHOT_STATE" in
    "SUCCESS")
      echo "[SUCCESS] 快照 ${SNAPSHOT_NAME} 已完成！"
      break
      ;;
    "IN_PROGRESS")
      echo "[INFO] 快照进行中（${i}/${MAX_RETRIES}），等待 ${RETRY_INTERVAL}秒..."
      sleep "$RETRY_INTERVAL"
      ;;
    "FAILED")
      fail "快照失败！状态: ${SNAPSHOT_STATE}。详情见 ${TMP_FILE}"
      ;;

    *)
      fail "未知快照状态: ${SNAPSHOT_STATE}"
      ;;
  esac
done
[[ "$SNAPSHOT_STATE" != "SUCCESS" ]] && fail "快照超时未完成"
# ===== 3. 查询快照中的索引 =====
echo "[STEP 2] 查询快照 ${SNAPSHOT_NAME} 中的索引...">>${LOG_FILE}
SNAPSHOT_INDICES=$(curl -sS -u "$ES_USER:$ES_PASS" "${ES_HOST}/_snapshot/${SNAPSHOT_REPO}/${SNAPSHOT_NAME}" |jq -r '.snapshots[0].indices[]')
echo $SNAPSHOT_INDICES
if [[ -z "$SNAPSHOT_INDICES" ]]; then
  echo "[WARN] 快照中无匹配索引，跳过删除"
  exit 0
fi
SQL="INSERT INTO t_oparea_es_detail (es_id, task_id, tasklog_id, index_name, repo_name, action_type, oparea_date, snap_name, create_date, modifyTime, remark) VALUES "
for index in $SNAPSHOT_INDICES; do
  echo "[DELETE] 删除索引: $index"
  curl -sS  -u "$ES_USER:$ES_PASS" -XDELETE "${ES_HOST}/$index"
  if [ $? -eq 0 ]; then
     echo "$index删除-> 成功"
     SQL+="('${es_id}','-999','${tasklog_id}','$index', '${SNAPSHOT_REPO}','1','${opearetime}','${SNAPSHOT_NAME}','${opearetime}','${opearetime}',''),"
  else
    indexmessage="${index} 删除失败,请手工删除索引"
    echo $message>>${LOG_FILE}
    send_text_message $indexmessage
  fi
done
echo "操作完成：快照 $SNAPSHOT_NAME 已创建，相关索引已删除">>${LOG_FILE}
SQL=${SQL%,}
echo $SQL>>${LOG_FILE}
mysql -h$HOST -u$USER -p$PASS $DB -e "$SQL"
if [ $? -eq 0 ]; then
  echo "操作完成：插入日志">>${LOG_FILE}
else
  echo "插入明细记录失败">>${LOG_FILE}
fi